from extensions import db
from datetime import datetime, date
from werkzeug.security import generate_password_hash, check_password_hash

class Event(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    # 全局配额（如果没有为特定日期设置配额，则使用此值）
    quota = db.Column(db.Integer, default=100)
    start_time = db.Column(db.DateTime, nullable=False)
    end_time = db.Column(db.DateTime, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.now)
    bookings = db.relationship('Booking', backref='event', lazy=True)
    date_quotas = db.relationship('DateQuota', backref='event', lazy=True)

class DateQuota(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    event_id = db.Column(db.Integer, db.ForeignKey('event.id'), nullable=False)
    date = db.Column(db.Date, nullable=False)
    quota = db.Column(db.Integer, nullable=False)
    # 确保每个赛事的每个日期只有一个配额记录
    __table_args__ = (db.UniqueConstraint('event_id', 'date'),)

    def __repr__(self):
        return f'<DateQuota {self.event_id} {self.date} {self.quota}>'

class Booking(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    event_id = db.Column(db.Integer, db.ForeignKey('event.id'), nullable=False)
    order_number = db.Column(db.String(20), unique=True)
    name = db.Column(db.String(30), nullable=False)
    phone = db.Column(db.String(11), nullable=False)
    id_type = db.Column(db.String(20), nullable=False)
    id_number = db.Column(db.String(20), nullable=False)
    booking_date = db.Column(db.Date, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.now)
    is_valid = db.Column(db.Boolean, default=True)
    verified_at = db.Column(db.DateTime)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(100))
    is_admin = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.now)
    last_login = db.Column(db.DateTime)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return f'<User {self.username}>'